package com.xytc.company.company_backend.adminEndPoint.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xytc.company.company_backend.adminEndPoint.entity.dao.CompanyInfoDao;
import com.xytc.company.company_backend.adminEndPoint.entity.dao.CompanyMenuDao;
import com.xytc.company.company_backend.adminEndPoint.entity.rto.CompanyMenuRto;
import com.xytc.company.company_backend.adminEndPoint.mapper.ICompanyInfoMapper;
import com.xytc.company.company_backend.adminEndPoint.mapper.ICompanyMenuMapper;
import com.xytc.company.company_backend.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.MessageFormat;
import java.util.Date;
import java.util.List;

/**
 * 为公司配置 套餐 菜单
 */
@Slf4j
@RestController
@RequestMapping("/company/companyMenuManage")
public class CompanyMenuManageController {

    @Autowired
    private ICompanyInfoMapper companyInfoMapper;

    @Autowired
    private ICompanyMenuMapper companyMenuMapper;

    /**
     * 接口2.1 新增或编辑 公司菜单
     *
     * @param companyMenuRto
     * @return
     */
    @PostMapping("/addOrUpdateCompanyMenu")
    public Result<?> addOrUpdateStore(@RequestBody CompanyMenuRto companyMenuRto) {

        CompanyMenuDao companyMenuDao = new CompanyMenuDao();
        companyMenuDao.setCompanyId(companyMenuRto.getCompanyId());
        companyMenuDao.setStartDate(companyMenuRto.getStartDate());
        companyMenuDao.setEndDate(companyMenuRto.getEndDate());
        companyMenuDao.setMenuType(companyMenuRto.getMenuType());
        companyMenuDao.setMenuDetails(companyMenuRto.getMenuDetails());
        companyMenuDao.setSendTime(companyMenuRto.getSendTime());

        if (StringUtils.isBlank(companyMenuRto.getMenuId())) {
            // 若菜单id为null，则表示 新增菜单
            String startDate = companyMenuRto.getStartDate();
            String endDate = companyMenuRto.getEndDate();
            String companyId = companyMenuRto.getCompanyId();
            // 查询出新添加的菜单的起始时间和结束时间，是否与已有的菜单的起始时间和结束时间重合
            List<CompanyMenuDao> list = companyMenuMapper.selectList(
                    new LambdaQueryWrapper<CompanyMenuDao>()
                            .eq(CompanyMenuDao::getDelFlag, 0)
                            .eq(CompanyMenuDao::getCompanyId, companyId)
                            .eq(CompanyMenuDao::getStatus, 1)
                            .between(CompanyMenuDao::getStartDate, startDate, endDate).
                            or(queryWapper -> queryWapper.between(CompanyMenuDao::getEndDate, startDate, endDate)));

            if (list != null || list.size() > 0) {
                // 若 某个公司新添加的菜单时间与之前为该公司配置的菜单时间范围冲突，这提示错误，不允许
                CompanyMenuDao existedCompanyMenuDao = list.get(0);
                String msg = MessageFormat.format("公司 {} 已经在 {} - {} 时间段配置了菜单，与新增菜单时间 {}-{} 冲突",
                        existedCompanyMenuDao.getCompanyId(),existedCompanyMenuDao.getStartDate(), existedCompanyMenuDao.getEndDate(),
                        existedCompanyMenuDao.getStartDate(), existedCompanyMenuDao.getEndDate());
                log.error(msg);
                return Result.error(500, msg);
            }

            companyMenuDao.setStatus(1);
            companyMenuDao.setCreateTime(new Date());

            companyMenuMapper.insert(companyMenuDao);
            JSONObject resultData = new JSONObject();
            resultData.put("menuId", companyMenuDao.getMenuId());
            resultData.put("message", "为公司新增菜单完成");

            return Result.ok(resultData);
        } else {
            // 若菜单id不为null，则表示 更新菜单，菜单中有多个套餐，没个套餐在 xy_company_menu 表中对应一条记录
            companyMenuDao.setMenuId(companyMenuRto.getMenuId());
            companyMenuMapper.updateById(companyMenuDao);

            return Result.ok();
        }
    }

    /**
     * 接口2.2 根据公司名称，查询为公司配置的 菜单
     *
     * @param keyword  为null或空字符串，这sql语句中，like "%%"，即不设置过滤条件
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("/queryCompanyInfoByKeyword")
    public Result<?> queryCompanyInfoByKeyword(@RequestParam("keyword") String keyword,
                                        @RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,
                                        @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) {

        Page<CompanyInfoDao> page = new Page<>(pageNo, pageSize);
        Page<CompanyInfoDao> pageList = companyInfoMapper.selectPage(page, new LambdaQueryWrapper<CompanyInfoDao>()
                .eq(CompanyInfoDao::getDelFlag, 0).like(CompanyInfoDao::getCompanyName, keyword));

        JSONArray formatedCompanyInfos = new JSONArray();
        pageList.getRecords().forEach(companyInfo -> {

            JSONObject formatedCompanyInfo = new JSONObject();
            formatedCompanyInfo.put("companyId", companyInfo.getId());
            formatedCompanyInfo.put("companyName", companyInfo.getCompanyName());
            formatedCompanyInfo.put("companyHr", companyInfo.getCompanyHr());
            formatedCompanyInfo.put("hrPhone", companyInfo.getHrPhone());
            formatedCompanyInfo.put("companyAddress", companyInfo.getCompanyAddress());
            formatedCompanyInfo.put("companyOrderUrl", companyInfo.getCompanyOrderUrl());
            formatedCompanyInfo.put("companyStartDate", companyInfo.getCompanyStartDate());
            formatedCompanyInfo.put("status", companyInfo.getStatus());

            formatedCompanyInfos.add(formatedCompanyInfo);
        });

        JSONObject resultData = new JSONObject();
        resultData.put("totalPages", pageList.getPages());
        resultData.put("totalCount", pageList.getTotal());
        resultData.put("currentPage", pageList.getCurrent());
        resultData.put("companyInfos", formatedCompanyInfos);

        return Result.ok(resultData);
    }

    /**
     * 接口2.2 根据公司id，查询为公司配置的所有菜单，按照菜单的起始时间倒序排序
     *
     * @param companyId  公司id
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("/queryCompanyMenu")
    public Result<?> queryCompanyMenu(@RequestParam("companyId") String companyId,
                                               @RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,
                                               @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) {

        Page<CompanyMenuDao> page = new Page<>(pageNo, pageSize);
        Page<CompanyMenuDao> pageList = companyMenuMapper.selectPage(page, new LambdaQueryWrapper<CompanyMenuDao>()
                .eq(CompanyMenuDao::getDelFlag, 0).like(CompanyMenuDao::getCompanyId, companyId).orderByDesc(CompanyMenuDao::getStartDate));

        JSONArray formatedCompanyMenus = new JSONArray();
        pageList.getRecords().forEach(companyMenu -> {

            JSONObject formatedCompanyMenu = new JSONObject();
            formatedCompanyMenu.put("menuId", companyMenu.getMenuId());
            formatedCompanyMenu.put("companyId", companyMenu.getCompanyId());
            formatedCompanyMenu.put("menuType", companyMenu.getMenuType());
            formatedCompanyMenu.put("menuDetails", JSONArray.parseArray(companyMenu.getMenuDetails()));
            formatedCompanyMenu.put("sendTime", companyMenu.getSendTime());
            formatedCompanyMenu.put("startDate", companyMenu.getStartDate());
            formatedCompanyMenu.put("endDate", companyMenu.getEndDate());
            formatedCompanyMenu.put("status", companyMenu.getStatus());

            formatedCompanyMenus.add(formatedCompanyMenu);
        });

        JSONObject resultData = new JSONObject();
        resultData.put("totalPages", pageList.getPages());
        resultData.put("totalCount", pageList.getTotal());
        resultData.put("currentPage", pageList.getCurrent());
        resultData.put("companyInfos", formatedCompanyMenus);

        return Result.ok(resultData);
    }


    /**
     * 接口3.3 切换包装套件状态
     * @param companyId
     * @param companyMenuId
     * @param status 1 表示上架中；2 表示下架
     * @return
     */
    @PutMapping("/changeCompanyMenuState")
    public Result<?> changeCompanyMenuState(@RequestParam("companyId") String companyId,
                                            @RequestParam("companyMenuId") String companyMenuId, @RequestParam("status") Integer status) {

        CompanyMenuDao companyMenuDao = new CompanyMenuDao();
        companyMenuDao.setMenuId(companyMenuId);
        companyMenuDao.setStatus(status);

        try{
            companyMenuMapper.updateById(companyMenuDao);
            log.info("公司{}，菜单{}状态更新成功，成功更新为 {}", companyId, companyMenuId, status);
            return Result.ok("公司菜单状态更新成功");
        }catch (Exception ex) {
            log.error("切换公司菜单状态失败 {}",ex);
            return Result.error(500,"公司菜单状态更新成功");
        }
    }

}
